<template>
  <div class="login-register-wrapper">
    <!-- 添加标题 -->
    <h1 class="page-title">中医药进销存ProMax</h1>
    <div class="login-register-container">
      <!-- 左侧欢迎信息和切换链接 -->
      <div class="left-section">
        <h2 class="welcome-text">Hello, Welcome!</h2>
        <div class="register-link">
          <span v-if="isLogin" style="font-size:17px;margin:10px 5px 5px 5px">还没有账号?</span>
          <span v-else style="font-size:17px;margin-bottom: 5px;margin-left: 5px;">已经有账号了?</span>
          <el-link type="primary" @click="toggleMode" style="font-size:25px;margin-top: -6px;margin-left: 2px;color: white;">
            {{ isLogin? '注册' : '登录' }}
          </el-link>
        </div>
      </div>
      <!-- 右侧表单区域 -->
      <div class="right-section">
        <!-- 将 v-if 和 v-else 移到 transition 外面 -->
        <div v-if="isLogin">
          <transition name="slide">
            <div class="form-container">
              <h2 class="form-title">登录</h2>
              <el-form :model="form" :rules="loginRules" ref="loginFormRef" label-width="auto" class="login-form">
                <el-form-item label="Username" prop="username">
                  <el-input v-model="form.username" placeholder="Username" />
                </el-form-item>
                <el-form-item label="Password" prop="password">
                  <el-input
                      v-model="form.password"
                      type="password"
                      placeholder="Password"
                      show-password
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleLogin" style="margin-left: 100px;margin-top: 10px">登 录</el-button>
                </el-form-item>
              </el-form>
            </div>
          </transition>
        </div>
        <div v-else>
          <transition name="slide">
            <div class="form-container">
              <h2 class="form-title">注 册</h2>
              <el-form :model="form" :rules="registerRules" ref="registerFormRef" label-width="auto" class="login-form">
                <el-form-item label="Username" prop="username">
                  <el-input v-model="form.username" placeholder="Username" />
                </el-form-item>
                <el-form-item label="Password" prop="password">
                  <el-input
                      v-model="form.password"
                      type="password"
                      placeholder="Password"
                      show-password
                  />
                </el-form-item>
                <el-form-item label="Confirm Password" prop="confirmPassword">
                  <el-input
                      v-model="form.confirmPassword"
                      type="password"
                      placeholder="Confirm Password"
                      show-password
                  />
                </el-form-item>
                <el-form-item label="Role" prop="role">
                  <el-select v-model="form.role" placeholder="请选择身份">
                    <el-option label="管理员" value="admin" />
                    <el-option label="客户" value="customer" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleRegister" >注 册</el-button>
                </el-form-item>
              </el-form>
            </div>
          </transition>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import request from '@/utils/request.js';
import { useRouter } from 'vue-router';
import axios from 'axios';

// 表单数据
const form = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  role: 'admin', // 默认角色为客户
});

// 是否为登录状态，true 为登录，false 为注册
const isLogin = ref(true);

// 登录表单引用
const loginFormRef = ref<FormInstance>();
// 注册表单引用
const registerFormRef = ref<FormInstance>();

// 登录表单验证规则
const loginRules: FormRules = {
  username: [
    { required: true, message: 'Please enter your username', trigger: 'blur' },
  ],
  password: [
    { required: true, message: 'Please enter your password', trigger: 'blur' },
  ],
};

// 注册表单验证规则
const registerRules: FormRules = {
  username: [
    { required: true, message: 'Please enter your username', trigger: 'blur' },
  ],
  password: [
    { required: true, message: 'Please enter your password', trigger: 'blur' },
    { min: 6, message: 'Password must be at least 6 characters', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: 'Please confirm your password', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.password) {
          callback(new Error('俩次输入的密码不一样'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
};

// 切换登录/注册模式
const toggleMode = () => {
  isLogin.value =!isLogin.value;
  // 切换模式时重置表单
  if (isLogin.value) {
    loginFormRef.value?.resetFields();
  } else {
    registerFormRef.value?.resetFields();
    form.role = 'customer'; // 重置时保持默认角色为客户
  }
};

// 处理登录提交
const router = useRouter()
const handleLogin = () => {
  loginFormRef.value?.validate((valid) => {
    if (valid) {
      request.post('user/login', {
        username: form.username,
        password: form.password
      }).then((res: any) => {
        if(res.code === 200 && res.message === "success"){
          // 存储用户信息和token
          localStorage.setItem("root_token", res.data.token);
          localStorage.setItem("user_role", res.data.userInfo.role);
          localStorage.setItem('user-Info', JSON.stringify(res.data.userInfo));

          sessionStorage.setItem('user-name', JSON.stringify(res.data.userInfo.username));
          sessionStorage.setItem('user-Info', JSON.stringify(res.data.userInfo));
          // 登录成功后
          // 设置默认的 Authorization 头
          axios.defaults.headers.common['Authorization'] = `Bearer ${res.data.token}`;

          ElMessage.success("登录成功！");

          console.log(res.data.userInfo);
          // 根据用户角色进行路由跳转
          if (res.data.userInfo.role === 'admin' || res.data.userInfo.role === 'merchant') {
            router.push('/manager/home');
          } else if (res.data.userInfo.role === 'customer') {
            router.push('/tcmmarket');
          } else {
            // 其他角色默认跳转到首页
            router.push('/tcmmarket');
          }
        } else {
          ElMessage.error("账号或密码错误");
        }
      }).catch(error => {
        ElMessage.error("登录失败，请稍后重试");
        console.error('Login error:', error);
      });
    } else {
      ElMessage.error('请正确填写所有必填字段');
    }
  });
};

// 处理注册提交
const handleRegister = () => {
  registerFormRef.value?.validate((valid) => {
    if (valid) {
      request.post('user/register', {
        username: form.username,
        password: form.confirmPassword,
        role: form.role
      }).then((res: any) => {
        if(res.code === 200){
          ElMessage.success("注册成功！去登陆");
          // 重置表单
          form.username = '';
          form.password = '';
          form.confirmPassword = '';
          form.role = 'customer';
          // 切换到登录模式
          isLogin.value = true;
        } else {
          ElMessage.error("注册失败");
        }
      }).catch(error => {
        ElMessage.error("注册失败，请稍后重试");
        console.error('Register error:', error);
      });
    } else {
      ElMessage.error('请正确填写所有必填字段');
    }
  });
};
</script>

<style scoped>
.login-register-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-image: url('../assets/back.jpg'); /* 替换为实际图片路径 */
  background-size: 100% 100%;

}

.page-title {
  font-size: 36px;
  color: #306d93; /* 标题颜色 */
  margin-bottom: 30px;
}

.login-register-container {
  display: flex;
  width: 800px;
  height: 450px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 86, 179, 0.2); /* 优化阴影 */
  overflow: hidden;
}

.left-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #5089ac; /* 优化左侧区域颜色 */
  color: white;
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
}

.welcome-text {
  font-size: 28px;
  margin-bottom: 20px;
}

.register-link {
  margin-top: 10px;
  text-align: center;
}

.right-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 30px;
  position: relative;
  overflow: hidden;
}

.form-title {
  font-size: 24px;
  margin-bottom: 30px;
}

.login-form {
  width: 100%;
  max-width: 400px;
}

.social-login {
  margin-top: 20px;
  text-align: center;
}

.forgot-password {
  margin-top: 10px;
  text-align: right;
}

/* 滑动过渡效果 */
.slide-enter-from {
  transform: translateX(100%);
  opacity: 0;
}

.slide-leave-to {
  transform: translateX(-100%);
  opacity: 0;
}

.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
}
</style>
